package com.yanmushi.ms.webconsole.controller;

import com.yanmushi.ms.webconsole.context.OAuthProperties;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther yinlei
 * @date 2018/1/23
 * @since 1.0.0
 */
@Controller
@RequestMapping("accept")
public class AcceptController {

    @Autowired
    OAuthProperties oAuthProperties;

    @RequestMapping("code")
    public String accept(String code, @CookieValue(value = "JSESSIONID", required = false) String sid, HttpSession session) {

        HttpClient client = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost(oAuthProperties.getTokenUri());

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type", "authorization_code"));
        params.add(new BasicNameValuePair("code", code));
        params.add(new BasicNameValuePair("client_id", oAuthProperties.getClientId()));
        params.add(new BasicNameValuePair("client_secret", oAuthProperties.getClientSecret()));
        params.add(new BasicNameValuePair("scope", "read"));
        params.add(new BasicNameValuePair("redirect_uri", "http://localhost:8081/accept/code"));

        post.setHeader("Cookie", "JSESSIONID=" + sid);

        try {
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // ignore
        }

        String body = "";

        try {
            HttpResponse rep = client.execute(post);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(rep.getEntity().getContent(), byteArrayOutputStream);
            body = new String(byteArrayOutputStream.toString("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        session.setAttribute("token", body);

        return "redirect:token";
    }

    @ResponseBody
    @RequestMapping("token")
    public String token(HttpSession session) {
        return (String) session.getAttribute("token");
    }
}
